package com.sunck.modules.system.controller;



import com.sunck.common.config.Global;
import com.sunck.common.exception.Result;
import com.sunck.common.exception.ResultUtil;
import com.sunck.common.shiro.SunckFormAuthenticationFilter;
import com.sunck.common.utils.ShiroUtils;
import com.sunck.modules.system.entity.User;
import com.sunck.modules.system.service.LoginService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * login 登录验证类
 *
 * @author LengChen
 * @version 1.0
 * @date 2020/8/4
 */
@Controller
public class LoginController {


    @Autowired
    private LoginService loginService;

    @GetMapping("/login")
    public String login(HttpServletRequest request, HttpServletResponse response)
    {
        if(ShiroUtils.getSysUser() != null){
            User user = ShiroUtils.getSysUser();
            // 登录成功后，验证码计算器清零
            loginService.isValidateCodeLogin(user.getLoginCode(), false, true);

            return "redirect:index";
        }
        return "login";
    }


    /**
     * 登录失败调用  登录鉴权由UserRealm & filter完成
     * @param model
     * @return
     */
    @ResponseBody
    @PostMapping("/login")
    public Result loginFail(String username, String password, HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
        String exception = (String)request.getAttribute(SunckFormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
        String message = (String)request.getAttribute(Global.DEFAULT_MESSAGE_PARAM);
        boolean mobile = WebUtils.isTrue(request, Global.DEFAULT_MOBILE_PARAM);

        // 非授权异常，登录失败，验证码加1。
        if (!UnauthorizedException.class.getName().equals(exception)){
            model.addAttribute("isValidateCodeLogin", loginService.isValidateCodeLogin(username, true, false));
        }

        return  ResultUtil.getResultErrByCode(message);
    }

    //注解验角色和权限
    @RequiresPermissions("user")
    @RequestMapping("/index")
    public String index() {
        return "index";
    }




}
